package edu.gxmzu.task.handler;

import com.alibaba.fastjson2.JSON;
import edu.gxmzu.task.utils.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.HttpRequestMethodNotSupportedException;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<String> handleMethodNotSupported(HttpRequestMethodNotSupportedException ex) {
        String errorMessage = "不支持的请求方法: " + ex.getMethod();
        return new ResponseEntity<>(JSON.toJSONString(Result.methodNotAllowed(errorMessage)), HttpStatus.METHOD_NOT_ALLOWED); // 返回 405 状态码
    }
    // 请求参数解析异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<String> handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
        String errorMessage = "参数解析异常: " + ex.getMessage();
        return new ResponseEntity<>(JSON.toJSONString(Result.badRequest(errorMessage)), HttpStatus.METHOD_NOT_ALLOWED);
    }
}